
package net.htjs.mobile.qxoa.gw;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Random;

import net.htjs.mobile.qxoa.LoginActivity;
import net.htjs.mobile.qxoa.R;
import net.htjs.mobile.qxoa.util.FileDownLoadThread;
import net.htjs.mobile.qxoa.util.L;
import net.htjs.mobile.qxoa.util.Util;
import net.htjs.mobile.qxoa.util.UtilIntent;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ListGwWebView extends Activity {
        private WebView webView;
        private static String LX="";
        ProgressDialog progressDialog, xh_pDialog;
        static int xh_count;
        // 获取SD卡目录
        private static String dowloadDir = Environment
                        .getExternalStorageDirectory() + "/ideasdownload/";
        private String filePath = "";

        public boolean onKeyDown(int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                        switch (keyCode) {
                        case KeyEvent.KEYCODE_BACK:
                                if (webView.canGoBack() == true) {
                                        webView.goBack();
                                } else {
                                        finish();
                                }
                                return true;
                        }

                }
                return super.onKeyDown(keyCode, event);
        }
        public void callPhone(String url){
        	Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse(url));
    	    
        	ListGwWebView.this.startActivity(intent);
        }
        public void onCreate(Bundle b) {
                super.onCreate(b);
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                this.setContentView(R.layout.gw_webview);

                webView = (WebView) this.findViewById(R.id.webviewFirst);
                webView.getSettings().setJavaScriptEnabled(true);

                
                // 提示信息对话框初始化
                progressDialog = new ProgressDialog(ListGwWebView.this);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setTitle("请稍等");
                progressDialog.setMessage("正在读取数据中!");

                // 提示信息对话框控制对象
                final GetListHandler handler = new GetListHandler();

                // 显示提示信息对话框
                progressDialog.show();

                // 设置webView客户端加载对象（为默认浏览器组件）
                webView.setWebViewClient(new WebViewClient() {
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            if(url.toLowerCase().startsWith("tel:")){
                            	callPhone(url);
                            	//Util.dialogProcess(getApplicationContext(), "拨打电话 "+url.replace("tel:", ""), "拨打", "取消", ListGwWebView.this, "callPhone", new Object[]{url}, null, null, null);
                            	return true;
                            }
                            else if (url.contains("main.jsp")
                                                || url.contains("/server/3g/index.jsp")) {
                                        finish();

                                        return true;
                                }
                            view.loadUrl(url);
                            return true;
                        }

                        // 页面加载前调方法定义
                        public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        	 
                                if (!progressDialog.isShowing())
                                        progressDialog.show();

                                L.l(url + " ------------------------------------");
                                if(url.toLowerCase().startsWith("tel:")){
                                	//Util.dialogProcess(getApplicationContext(), "拨打电话 "+url.replace("tel:", ""), "拨打", "取消", ListGwWebView.this, "callPhone", new Object[]{url}, null, null, null);
                                	callPhone(url);
                                	return;
                                }
                                if (url.contains("/server/3g/index.jsp")) {
                                        Intent intent = new Intent();
                                        intent.setClass(ListGwWebView.this, LoginActivity.class);
                                        startActivity(intent);
                                        finish();
                                        return;
                                } else if (url.contains("main.jsp")) {
                                        finish();
                                        // webView.onKeyDown(KeyEvent.KEYCODE_BACK, null);
                                        return;
                                } else if (url.contains("fileDown.jsp")) {
                                        /*
                                         * Intent intent = new Intent(); Bundle bundle = new
                                         * Bundle(); bundle.putString(L.FileDownLoad.URL, url);
                                         * String fileName = url.substring(url.lastIndexOf("=") +
                                         * 1); String urlAfter = url.substring(0,
                                         * url.lastIndexOf("&")); String id =
                                         * urlAfter.substring(urlAfter.lastIndexOf("=") + 1); L.l(id
                                         * + "++++++++++++++++++++++++");
                                         * bundle.putString(L.FileDownLoad.FILENAME, id);
                                         * bundle.putString(L.FileDownLoad.FILETYPE, ".doc");
                                         * intent.setClass(ListGwWebView.this, FileDownLoad.class);
                                         * intent.putExtras(bundle); startActivity(intent);
                                         */

                                        String urlAfter = url.substring(0, url.lastIndexOf("&"));
                                        String id = urlAfter.substring(urlAfter.lastIndexOf("=") + 1);
                                        L.l(id + "++++++++++++++++++++++++");

                                        filePath = dowloadDir + id + ".doc";
                                        /* File fileP = new File(filePath);
                                        if (fileP.exists()) {
                                                Util.dialog(ListGwWebView.this, "文件已经存在，是否重新下载？",
                                                                "重新下载", "取消", ListGwWebView.this, "download",
                                                                new String[] { url, filePath },
                                                                ListGwWebView.this, "openFile", new String[] {
                                                                                url, filePath }, true);
                                                // dialog("文件已经存在，是否重新下载？", "重新下载", "取消");
                                        } else*/
                                                download(url, filePath);

                                        return;
                                }
                                super.onPageStarted(view, url, favicon);
                        }

                        // 页面加载回调方法定义
                        public void onPageFinished(WebView view, String url) {
                                // TODO Auto-generated method stub
                                new Thread(new Runnable() {

                                        public void run() {
                                                // TODO Auto-generated method stub
                                                Message msg = handler.obtainMessage();
                                                handler.sendMessage(msg);
                                        }

                                }).start();
                                super.onPageFinished(view, url);

                        }

                });
                // 得到上个activity传入的参数信息
                Bundle bundle = this.getIntent().getExtras();
                String URL = "";
                String lx = bundle.getString(L.LX);
                LX=lx;
                Cookie sessionCookie=null;
                if(LX.equals(L.Nine.DZYX)){
                	sessionCookie = L.mailcookie;
                }else{
                	sessionCookie = L.cookie;
                }
                // 这里的cookie就是上面保存的cookie，
                // 设置模拟cookie，提供客户端服务器认证凭证
                CookieSyncManager.createInstance(this);
                CookieManager cookieManager = CookieManager.getInstance();
                if (sessionCookie != null) {
                        // cookieManager.removeSessionCookie();
                        String cookieString = sessionCookie.getName() + "="
                                        + sessionCookie.getValue() + "; domain="
                                        + sessionCookie.getDomain();
                        cookieManager.setCookie(L.baseDomain, cookieString);
                        CookieSyncManager.getInstance().sync();
                }

               
                if (L.Nine.GW.endsWith(lx) || L.Nine.XW.equals(lx)) {
                        String zt = bundle.getString(L.ZT);
                        URL = L.gwListWapUrl + "&ZT=" + zt + "&CZRY_DM="
                                        + L.status.get("CZRY_DM") + "&JSESSIONID="
                                        + L.status.get("JSESSIONID");
                } else if (L.Nine.DZGG.endsWith(lx)) {
                        URL = L.dzggUrl + "&CZRY_DM=" + L.status.get("CZRY_DM")
                                        + "&JSESSIONID=" + L.status.get("JSESSIONID");
                } else if (L.Nine.DZYX.endsWith(lx)) {
                        URL = L.dzyxUrl+L.Nine.MAILSESSIONID;

                } else if (L.Nine.GZZD.endsWith(lx)) {
                        URL = L.gzzdUrl + "&CZRY_DM=" + L.status.get("CZRY_DM")
                                        + "&JSESSIONID=" + L.status.get("JSESSIONID");
                } else if (L.Nine.TXL.endsWith(lx)) {
                        URL = L.txlUrl + "&CZRY_DM=" + L.status.get("CZRY_DM")
                                        + "&JSESSIONID=" + L.status.get("JSESSIONID");
                }

                webView.loadUrl(URL, L.status);
                System.out.println(L.cookie);

        }

        class GetListHandler extends Handler {
                @Override
                public void handleMessage(Message msg) {
                        progressDialog.dismiss();// 关闭进度条
                }
        }

        public void openFile(String args, String fileName) {
                Intent intent = UtilIntent.getWordFileIntent(fileName);
                startActivity(intent);
        }

        public void download(final String url, String fileName) {

                /*
                 * 下载进度条初始化
                 */
                xh_count = 0;

                // 创建ProgressDialog对象
                xh_pDialog = new ProgressDialog(ListGwWebView.this);

                // 设置进度条风格，风格为长条形的
                xh_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

                xh_pDialog.setTitle("下载提示");
                xh_pDialog.setMessage("下载文件进度");
                xh_pDialog.setIndeterminate(false);
                xh_pDialog.setProgress(100);
                xh_pDialog.setIcon(R.drawable.logonyoa);

                xh_pDialog.setCancelable(true);

                xh_pDialog.show();

                new Thread() {
                        @Override
                        public void run() {
                                try {
                                        while (xh_count>=0&&xh_count < 100) {
                                                // 由线程来控制进度
                                                xh_pDialog.setProgress(xh_count);
                                                Thread.sleep(100);
                                        }
                                        if(xh_count<0){
                                        	Util.dialog(ListGwWebView.this, "下载失败，是否重新下载？",
                                                    "重新下载", "取消", ListGwWebView.this, "download",
                                                    new String[] { url, filePath },
                                                    null, "openFile", new String[] {
                                                                    url, filePath }, false);
                                        	
                                        }else{
                                        	xh_pDialog.cancel();
                                            Thread.sleep(500);
                                            Intent intent = UtilIntent.getWordFileIntent(filePath);
                                            startActivity(intent);
                                        }
                                        
                                } catch (Exception e) {
                                        xh_pDialog.cancel();
                                }
                        }
                }.start();
                // 获取SD卡目录
                File file = new File(dowloadDir);
                // 创建下载目录
                if (!file.exists()) {
                        file.mkdirs();
                }

                // 读取下载线程数，如果为空，则单线程下载
                int downloadTN = 1;

                new downloadTask(url, Integer.valueOf(downloadTN), fileName).start();
        }

        /**
         * @author ideasandroid 主下载线程
         */
        public class downloadTask extends Thread {
                private int blockSize, downloadSizeMore;
                private int threadNum = 5;
                String urlStr, threadNo, fileName;

                public downloadTask(String urlStr, int threadNum, String fileName) {
                        this.urlStr = urlStr;
                        this.threadNum = threadNum;
                        this.fileName = fileName;
                }

                @Override
                public void run() {
                        FileDownLoadThread[] fds = new FileDownLoadThread[threadNum];
                        try {
                                HttpPost request = new HttpPost(urlStr);
                                DefaultHttpClient client = new DefaultHttpClient();
                                HttpResponse httpResponse = client.execute(request);

                                File file = new File(fileName);
                                /*
                                 * if(!file.exists()){ file.createNewFile(); }
                                 */
                                RandomAccessFile fos = new RandomAccessFile(file, "rw");
                                fos.write(EntityUtils.toByteArray(httpResponse.getEntity()));
                                byte[] ab = new byte[1024];
                                fos.read(ab, 0, 1024);
                                System.out.println(new String(ab));
                                fos.close();

                                xh_count = new Random().nextInt(30) + 20;

                                sleep(300);
                                xh_count = new Random().nextInt(50) + 20;

                                sleep(300);
                                xh_count = new Random().nextInt(70) + 20;

                                sleep(300);
                                xh_count = 100;
                                sleep(300);

                        } catch (Exception e) {
                        		xh_count=-1;
                                e.printStackTrace();
                        }

                }
        }
}